# -*- coding: utf-8 -*-

import wx
import wx.grid

from threading      import Thread
from itertools      import cycle
from assis_const    import * 
from assis_cloud    import *
from assis_settings import *
from assis_config   import *


class Frame(wx.Frame):
	
	def __init__(self, ion, google, *args, **kwds):
		
		kwds["style"] = wx.DEFAULT_FRAME_STYLE
		wx.Frame.__init__(self, *args, **kwds)
		
		self.result_set_grid       = wx.grid.Grid(self, -1, size=(1, 1))
		self.search_input          = wx.TextCtrl(self, -1, "", style = wx.TE_PROCESS_ENTER)
		self.search_button         = wx.Button(self, -1, "Search")
		self.next_button           = wx.Button(self, -1, "Next")
		self.history_combo_box     = wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)
		self.static_line_1         = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)
		self.cloud_vocabulary_grid = wx.grid.Grid(self, -1, size=(1, 1))
		self.google_info_label     = wx.StaticText(self, -1, "Tamas.Gombar@Gmail.com")
		self.sheet_combo_box       = wx.ComboBox(self, -1, choices=[], style=wx.CB_DROPDOWN)
		self.activity_flag_bitmap  = wx.StaticBitmap(self, -1, wx.NullBitmap)
		self.ion                   = ion
		self.local_dict            = self.ion.history
		self.ring                  = cycle(self.local_dict.keys())
		self.key                   = next(self.ring)
		self.google                = google
		self.__set_properties()
		self.__do_layout()
		self.next_button.Bind(wx.EVT_BUTTON, self.next)
		self.search_button.Bind(wx.EVT_BUTTON, self.search)
		self.search_input.Bind(wx.EVT_TEXT_ENTER, self.search)
		self.history_combo_box.Bind(wx.EVT_COMBOBOX, self.next)
		self.sheet_combo_box.Bind(wx.EVT_COMBOBOX, self.load_sheet)
		self.populate_history()
		self.populate_worksheets()
		self.next(None)
		
	def drop_results(self, both = None):
		
		for i in range(self.result_set_grid.GetNumberRows()):
			self.result_set_grid.SetCellValue(i, 0, "")
			self.result_set_grid.SetCellValue(i, 1, "")

	def search(self, event):
		
		word = self.search_input.GetValue().encode("utf-8", "ignore")
		self.ion.translate(word)
		self.ring = cycle(self.local_dict.keys())
		self.populate_history(self.ion.last_sought)
		self.next(event, self.ion.get_last_dict())

	def next(self, event, new_dict = None):
		
		#DB key selected from combo box
		if event is not None:
			if len(event.GetString()) > 0:
				self.key = event.GetString().encode("utf-8", "ignore")
				one_dict = self.local_dict.get(self.key)
		#Default case; Next button pressed
		if new_dict is None:
			self.key = next(self.ring)
			one_dict = self.local_dict.get(self.key)
		#new_dict created by searching a new word
		else:
			one_dict = new_dict

		self.drop_results()
		self.populate(one_dict)

	def populate(self, one_dict):
		
		i = 0
		for k, v in one_dict.items():
			self.result_set_grid.SetCellValue(i, 0, self.render_tuple(k))
			self.result_set_grid.SetCellValue(i, 1, self.render_tuple(v))
			i += 1

	def render_tuple(self, tuple):
		
		return reduce(lambda string, item: string + item + " ", tuple)

	def populate_history(self, new_key = None):
		
		if new_key is not None:
			self.history_combo_box.Append(new_key)
			return
			
		for key in self.local_dict:
			self.history_combo_box.Append(key)

	def populate_worksheets(self):
		
		self.sheet_combo_box.Clear()
		for item in self.google.get_worksheets():
			self.sheet_combo_box.Append(item)

	def load_sheet(self, event):
		
		self.cloud_vocabulary_grid.ClearGrid()
		self.google.set_wrksht_id(self.sheet_combo_box.GetSelection())
		worksheet = self.google.worksheet()
		for entry in worksheet:
			x, y = self.google.render_coordinates(entry.title.text)
			num_rows = self.cloud_vocabulary_grid.GetNumberRows()
			num_cols = self.cloud_vocabulary_grid.GetNumberCols()
			if y >= num_rows:
				self.cloud_vocabulary_grid.AppendRows(y - num_rows +1)
				
			if x >= num_cols:
				self.cloud_vocabulary_grid.AppendCols(x - num_cols +1)
				
			self.cloud_vocabulary_grid.SetCellValue(y, x, entry.content.text)
			
		self.cloud_vocabulary_grid.ForceRefresh()


	def __set_properties(self):

		self.SetTitle("Assis " + VERSION)
		self.SetSize((1000, 320))
		self.result_set_grid.CreateGrid(8, 2)
		self.result_set_grid.SetRowLabelSize(0)
		self.result_set_grid.SetColLabelSize(25)
		self.result_set_grid.EnableDragGridSize(0)
		self.result_set_grid.SetColLabelValue(0, "English")
		self.result_set_grid.SetColSize(0, 245)
		self.result_set_grid.SetColLabelValue(1, "Hungarian")
		self.result_set_grid.SetColSize(1, 245)
		self.result_set_grid.SetMinSize((485, 270))
		self.search_input.SetMinSize((140, 28))
		self.search_button.SetMinSize((75, 28))
		self.next_button.SetMinSize((75, 28))
		self.history_combo_box.SetMinSize((200, 28))
		self.static_line_1.SetMinSize((3, 315))
		self.static_line_1.SetBackgroundColour(wx.Colour(0, 0, 0))
		self.static_line_1.SetForegroundColour(wx.Colour(0, 0, 0))
		self.static_line_1.SetToolTipString("Assis")
		self.cloud_vocabulary_grid.CreateGrid(0,0)
		self.cloud_vocabulary_grid.SetRowLabelSize(20)
		self.cloud_vocabulary_grid.SetColLabelSize(25)
		self.cloud_vocabulary_grid.EnableDragGridSize(0)
		self.cloud_vocabulary_grid.SetMinSize((500, 270))
		self.google_info_label.SetMinSize((220, 22))
		self.sheet_combo_box.SetMinSize((193, 28))
		self.activity_flag_bitmap.SetMinSize((24, 24))
		self.activity_flag_bitmap.SetBackgroundColour(wx.Colour(255, 127, 0))
		self.activity_flag_bitmap.SetForegroundColour(wx.Colour(255, 127, 0))

	def __do_layout(self):

		sizer_1 = wx.BoxSizer(wx.VERTICAL)
		sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_4 = wx.BoxSizer(wx.VERTICAL)
		sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_3 = wx.BoxSizer(wx.VERTICAL)
		sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_3.Add(self.result_set_grid, 1, wx.EXPAND, 0)
		sizer_5.Add(self.search_input, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_5.Add(self.search_button, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_5.Add(self.next_button, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_5.Add(self.history_combo_box, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 10)
		sizer_3.Add(sizer_5, 1, wx.EXPAND, 0)
		sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
		sizer_2.Add(self.static_line_1, 0, wx.RIGHT|wx.EXPAND, 5)
		sizer_4.Add(self.cloud_vocabulary_grid, 1, wx.EXPAND, 0)
		sizer_6.Add(self.google_info_label, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_6.Add(self.sheet_combo_box, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_6.Add(self.activity_flag_bitmap, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_4.Add(sizer_6, 1, wx.EXPAND, 0)
		sizer_2.Add(sizer_4, 1, wx.EXPAND, 0)
		sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
		self.SetSizer(sizer_1)
		self.Layout()
		self.Centre()


class wxApplication(Thread, wx.App):
	
	def __init__(self, ion, logger = None):
		
		self.ion    = ion
		self.google = Google()
		self.config = Config()
		Thread.__init__(self)
		wx.App.__init__(self)
		
		
	def OnInit(self):
		
		if not self.config.iscomplete():
			settings_frame = CloudSettings(self.config, self.google, None, -1 , "")
			self.SetTopWindow(settings_frame)
			settings_frame.Show()
			self.MainLoop()
	
		return 1
	
	def run(self):

		wx.InitAllImageHandlers()
		main_frame  = Frame(self.ion, self.google, None, -1, "")
		self.SetTopWindow(main_frame)
		main_frame.Show()
		self.MainLoop()
